<?php
/**
 * Created by PhpStorm.
 * User: andy
 * Date: 2019/8/29
 * Time: 下午6:42
 */
namespace app\common\model;

use think\Model;
use think\facade\Cache;

class AdminMenuModel extends Model
{

    const C_TYPE = 0; //只作为菜单
    const Y_TYPE = 1; //有界面可访问菜单
    const W_TYPE = 2; //无界面可访问菜单

    const SHOW_STATUS=1; //显示
    const HIDE_STATUS=0; //不显示

    protected $autoWriteTimestamp = true;

    /**
     * 所有分类
     * @param $update //更新，1 更新，0 不更新
     * @return mixed
     */
    public static function getALL($update=0)
    {
        $model = new static;
        if (!Cache::get('auth_category') || $update) {
            $field="id,parent_id,type,status,list_order,app,controller,action,position,name,icon,remark";
            $data = $model->field($field)->order(['list_order' => 'asc', 'create_time' => 'asc'])->select();
            $all = !empty($data) ? $data->toArray() : [];
            $tree = [];
            foreach ($all as $first) {
                if($first["parent_id"]!=0) continue;

                $first['child'] = self::getAllMenu($all,$first['id']);;

                $tree[]=$first;
            }
            Cache::tag('cache')->set('auth_category', compact('all','tree'));
        }
        return Cache::get('auth_category');
    }

    /**
     * 所有子分类
     * @param $all
     * @param $id
     * @return array
     */
    private static function getAllMenu($all,$id){
        $arr=[];

        foreach ($all as $vo){
            if($vo["parent_id"]!=$id) continue;

            $vo['child'] = self::getAllMenu($all,$vo['id']);

            $arr[]=$vo;
        }

        return $arr;
    }

    /**
     * 所有显示菜单
     * @param $update //更新，1 更新，0 不更新
     * @return mixed
     */
    public static function getMenu($update=0,$user)
    {
        $model = new static;
        if (!Cache::get('menu_category') || $update) {
            $ag=AuthGroupModel::field('auth_list')->get($user->auth_id);

            $field="id,parent_id,type,status,list_order,app,controller,action,position,name,icon,remark";
            $query=$model->field($field)
                ->where('type',"<>",self::W_TYPE)
                ->where('status',self::SHOW_STATUS)
                ->order(['list_order' => 'asc', 'create_time' => 'asc']);

            if($user->id!=AdminUserModel::SUPER_USER_ID){
                $query->whereIn('id',$ag['auth_list']);
            }

            $data=$query->select();

            $all = !empty($data) ? $data->toArray() : [];
            $tree = [];
            foreach ($all as $first) {
                if ($first['parent_id'] != 0) continue;
                $twoTree = [];
                foreach ($all as $two) {
                    if ($two['parent_id'] != $first['id']) continue;
                    $threeTree = [];
                    foreach ($all as $three)
                        $three['parent_id'] == $two['id']
                        && $threeTree[$three['id']] = $three;
                    !empty($threeTree) && $two['child'] = $threeTree;
                    $twoTree[$two['id']] = $two;
                }
                if (!empty($twoTree)) {
                    array_multisort(array_column($twoTree, 'list_order'), SORT_ASC, $twoTree);
                    $first['child'] = $twoTree;
                }
                $tree[$first['id']] = $first;
            }
            Cache::tag('cache')->set('menu_category', compact('all', 'tree'));
        }
        return Cache::get('menu_category');
    }

    /**
     * 增加分类
     * @param $data
     * @return bool
     */
    public function addMenu($data){
        //检测当前应用方法名是否重复
        if(!self::chackAction($data)){
            return['status'=>0,'msg'=>'方法名已存在！'];
        }

        if(empty($data['id'])){
            $status = self::save($data);

            if($status){
                self::getALL(1);
                return['status'=>1,'msg'=>'增加成功！'];
            }else{
                return['status'=>0,'msg'=>'增加失败！'];
            }
        }else{
            $status = self::save($data,['id'=>$data["id"]]);

            if($status){
                self::getALL(1);
                return['status'=>1,'msg'=>'修改成功！'];
            }else{
                return['status'=>0,'msg'=>'修改失败！'];
            }
        }

    }

    /**
     * 删除
     * @param $id
     * @return array
     */
    public function del($id){
        $count=self::where('parent_id',$id)
            ->count();

        if($count>0){
            return ['status'=>0,'msg'=>'有子栏目不能删除！'];
        }

        $status=self::destroy($id);
        if($status){
            self::getALL(1);
            return ['status'=>1,'msg'=>'删除成功！'];
        }else{
            return ['status'=>0,'msg'=>'删除失败！'];
        }

    }

    /**
     * 检测当前应用方法名是否重复
     * @param $data
     * @return bool
     */
    public static function chackAction($data){
        if(empty($data['id'])){
            $data['id']=0;
        }

        $count=self::where('app',$data['app'])
            ->where('controller',$data["controller"])
            ->where('action',$data['action'])
            ->where('id',"<>",$data['id'])
            ->count();

        if($count>0){
            return false;
        }else{
            return true;
        }
    }

    /**
     * 面包屑
     * @param $modArr
     * @return array|bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function menuBread($modArr){
        $info=self::field("parent_id,name,app,controller,action")
            ->where('app',$modArr['app'])
            ->where('controller',$modArr["controller"])
            ->where('action',$modArr['action'])
            ->where('type','<>',self::W_TYPE)
            ->where('status',self::SHOW_STATUS)
            ->find();

        if(empty($info)){
            return false;
        }
        $info=$info->toArray();
        $info['now']=1; //当前页

        $arr[]=$info;

        if(!$info["parent_id"]){
            return $arr;
        }else{
            return array_reverse(array_merge_recursive($arr,self::getMenuParent($info["parent_id"])));
        }

    }

    /**
     * 面包屑父级
     * @param $pid
     * @return array
     * @throws \think\Exception\DbException
     */
    private function getMenuParent($pid){
        $info=self::field("parent_id,name,app,controller,action")->get($pid);

        $arr[]=$info->toArray();

        if(!$info["parent_id"]){
            return $arr;
        }else{
            return array_merge_recursive($arr,self::getMenuParent($info["parent_id"]));
        }
    }

}